#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：Employment_class 
@File    ：06_动态服务器_复习.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/7/15/015 22:19 
"""
import sys
from multiprocessing import Process
from socket import *


class WsgiServer(object):
    HTML_ROOT_DIR = "./html"
    WSGI_ROOT_DIR = "./wsgiPy"

    def __init__(self):
        self.sersocket = socket(AF_INET, SOCK_STREAM)
        self.sersocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.sersocket.bind(("", 7788))
        self.sersocket.listen(10)

    def serveForever(self):
        '循环运行web服务器，等待客户端的链接并为客户端服务'
        while True:
            # 等待新客户端到来
            self.clientSocket, client_address = self.sersocket.accept()

            # 方法2，多进程服务器，并发服务器于多个客户端
            newClientProcess = Process(target=self.handleRequest)
            newClientProcess.start()

            # 因为创建的新进程中，会对这个套接字+1，所以需要在主进程中减去依次，即调用一次close
            self.clientSocket.close()

    def start_seponse(self, status, headers):
        response_headers = "HTTP/1.1" + status + "\r\n"
        for header in headers:
            response_headers += "%s: %s\r\n" % header
        self.response_headers = response_headers

    def handleRequest(self):
        recvData = self.clientSocket.recv(1024)
        requestHeaderLines = recvData.splitlines()
        for line in requestHeaderLines:
            print(line)

        httpRequestMethodLine = requestHeaderLines[0]
        method = str(httpRequestMethodLine).split(" ")[0]
        file_name = str(httpRequestMethodLine).split(" ")[1]
        print("______filename1____%s" % file_name)
        if file_name.endswith(".py"):
            try:
                m = __import__(file_name[1:-3])
            except Exception:
                self.response_headers = "HTTP/1.1 404 not founds\r\n"
                response_body = "not found"
                response = self.response_headers + response_body
            else:
                env = {
                    "PATH_INFO": file_name,
                    "METHOD": method
                }
                response_body = m.application(env, self.start_seponse)
                response = self.response_headers + "\r\n" + response_body
            finally:
                print("response:",response)
                self.clientSocket.send(response.encode("gbk"))
                self.clientSocket.close()
        else:
            if file_name == "/":
                filename = self.HTML_ROOT_DIR + "/index.html"
            else:
                filename = self.HTML_ROOT_DIR + file_name
            try:
                f = open(filename, "r", encoding="gbk")
            except IOError:
                responseHeaderLines = "HTTP/1.1 404 not found\r\n"
                responseHeaderLines += "\r\n"
                responseBody = "====sorry ,file not found===="
            else:
                responseHeaderLines = "HTTP/1.1 200 OK\r\n"
                responseHeaderLines += "\r\n"
                responseBody = f.read()
                f.close()
            finally:
                response = responseHeaderLines + responseBody
                self.clientSocket.send(response.encode("gbk"))
                self.clientSocket.close()

def main():
    sys.path.insert(1,"./wsgiPy")
    WsgiServer().serveForever()

if __name__ == '__main__':
    main()
